{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "from surprise import SVD\n",
    "from surprise import Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_top_n(predictions, n=10):\n",
    "    '''Return the top-N recommendation for each user from a set of predictions.\n",
    "\n",
    "    Args:\n",
    "        predictions(list of Prediction objects): The list of predictions, as\n",
    "            returned by the test method of an algorithm.\n",
    "        n(int): The number of recommendation to output for each user. Default\n",
    "            is 10.\n",
    "\n",
    "    Returns:\n",
    "    A dict where keys are user (raw) ids and values are lists of tuples:\n",
    "        [(raw item id, rating estimation), ...] of size n.\n",
    "    '''\n",
    "\n",
    "    # First map the predictions to each user.\n",
    "    top_n = defaultdict(list)\n",
    "    for uid, iid, true_r, est, _ in predictions:\n",
    "        top_n[uid].append((iid, est))\n",
    "\n",
    "    # Then sort the predictions for each user and retrieve the k highest ones.\n",
    "    for uid, user_ratings in top_n.items():\n",
    "        user_ratings.sort(key=lambda x: x[1], reverse=True)\n",
    "        top_n[uid] = user_ratings[:n]\n",
    "\n",
    "    return top_n# Than predict ratings for all pairs (u, i) that are NOT in the training set.\n",
    "testset = trainset.build_anti_testset()\n",
    "predictions = algo.test(testset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<surprise.prediction_algorithms.matrix_factorization.SVD at 0x7f1977178240>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# First train an SVD algorithm on the movielens dataset.\n",
    "data = Dataset.load_builtin('ml-100k')\n",
    "trainset = data.build_full_trainset()\n",
    "algo = SVD()\n",
    "algo.fit(trainset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Than predict ratings for all pairs (u, i) that are NOT in the training set.\n",
    "testset = trainset.build_anti_testset()\n",
    "predictions = algo.test(testset)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "top_n = get_top_n(predictions, n=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
